require 'iconv'
class PaperAdminController < ApplicationController
    before_filter :authorize, :except => :login
    before_filter   :configure_charsets
    layout "common_layout"
     
   
  def configure_charsets   
    @headers["Content-Type"]="text/html; charset=utf-8" 
  end  
  
  def list
    @paper_pages, @papers = paginate :papers, :order => 'title DESC', :per_page => 10
  end
  
  def edit
    @paper = Paper.find(params[:id])
    if @paper.update_attributes(params[:paper])
      flash[:notice] = 'Paper was successfully updated.'
      redirect_to :action => 'show', :id => @paper
    else
      render :action => 'show'
    end
  end
  
  def add_paper
    
    unless request.get?
      begin
      @paper=Paper.new(params[:paper])
      @paper.user_id =session[:user_id]
      orignalfile=upload_file(params[:originalfile]['file'])
     # pptfile=upload_file(params[:pptfile]['file'])
     # transfile=upload_file(params[:transfile]['file'])
      @paper.save_url=orignalfile
      
      @paper.save!
      rescue ActiveRecord::RecordNotSaved
          delete_file(orignalfile)
      else
        flash[:notice] = 'Paper was successfully created.'
        redirect_to :action =>'list'   
      end
    end
    
  end
  
  def delete    
     paper=Paper.find(params[:id])
     delete_file(paper.save_url)
     paper.destroy
     redirect_to :action => 'list'
  end
  
  def show
    @paper = Paper.find(params[:id])
  end
  
def search
  if params[:query].to_s!=""
    @query = params[:query]
    @total, @searchResults = Paper.full_text_search(@query, :page => (params[:page]||1))        
  else
    redirect_to :action=>'no_result'
  end
  @pages = pages_for(@total)
end
   
  def delete_file(filename)
    File.delete("#{RAILS_ROOT}/uploadfile/#{filename}")
  end
  
  def upload_file(file)   
    if !file.original_filename.empty?   
      @filename=get_file_name(file.original_filename)
      File.open("#{RAILS_ROOT}/uploadfile/#{@filename}", "wb") do |f|   
        f.write(file.read)
      end   
      return @filename   
    end   
  end
  
  def download_file
    if params[:filename]
      send_file "#{RAILS_ROOT}/uploadfile/#{params[:filename]}"
    end
  end
  
  def get_file_name(filename)   
    if !filename.nil?   
      Time.now.strftime("%Y_%m_%d_%H_%M_%S") + '_' +Iconv.conv("gbk","utf-8",filename)
    end   
  end   
end
